package com.wx;

import com.wx.model.templatemessage.Keyworld;
import com.wx.model.templatemessage.WxTemplateMessage;
import com.wx.service.Impl.WXServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/12/6 3:01 下午
 * @desc ：
 */
@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class LastTemplateMsg {

    @Autowired
    WXServiceImpl wxService;


   public ArrayList<String> users =  new ArrayList<String>();

   public String templateId =  "o2ej4HgGt7z5ZwEiOTqvSGdp3uexccS_uhp7pXnVgb0";

    @Test
    public void  test (){
        users.add("oCV_T6IutImdnwuD658EyIMM_goU");
        users.add("oCV_T6M9Gl_5j61N0c1ve1Hx_Hr8");
        users.add("oCV_T6GpT16nNScrrZ7kaDawmxzM");
        users.add("oCV_T6NjiyyCyzj-JTClcweJDX84");
        users.add("oCV_T6NT0PFYkjmXYQyU7L8oFarU");
        users.add("oCV_T6HB6O-k0IMIB-fD_7bqhEQI");
        users.add("oCV_T6FlZ4U0EEhNlVi51udzQI8U");
        users.add("oCV_T6GUj67UKShxzFXbExpFYcYA");
        users.add("oCV_T6ONVcZ1vLdPjHOt6PsDliNc");
        users.add("oCV_T6Ag5EzQp95DXo5SwK-8RRlo");
        users.add("oCV_T6O5wZizupliRSrmnNjBs7lk");
        users.add("oCV_T6IA1QpOnfg-x4AMZYgT2ZSw");



        LocalDateTime today = LocalDateTime.now();
        String now = today.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
        LocalDateTime nextSaturDay = today.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
        LocalDateTime yuanDan = LocalDateTime.of(2022, 1, 1, 00, 00, 00, 00);
        LocalDateTime nian = LocalDateTime.of(2022, 1, 31, 00, 00, 00, 00);
        long l1 = Duration.between(today, nextSaturDay).toDays();
        long l4 = Duration.between(today, yuanDan).toDays();
        long l5 = Duration.between(today, nian).toDays();

        /**
         * 尊敬的会员，今天是{{keyword0.DATA}}，
         * 很遗憾的通知您，由于不可抗力的因素，本次是最后一次为您提供服务，以后不能在为您提供天气信息、新闻资讯、计时提醒以及人工智能服务了。如果您还想继续关注作者，
         * 可以通过以下途径：
         * - 微信公众号：TalkJava
         * - b站：Liu_Shihao
         * - csdn：https://blog.csdn.net/DreamsArchitects
         * 如果您想支持作者，为作者加油可以通过支付宝/微信打赏：15037196928。
         * 最后一次为您提供倒计时服务：
         * 距离本周周末还有{{keyword2.DATA}}天！
         * 距离跨年假期还有{{keyword3.DATA}}天!
         * 距离春节假期还有{{keyword4.DATA}}天!
         * 祝您生活愉快！
         *
         */
        Keyworld keyword0 = new Keyworld(now,"#FFE66F");
        Keyworld keyword1 = new Keyworld("TalkJava","#FF8040");
        Keyworld keyword2 = new Keyworld("Liu_Shihao","#E800E8");
        Keyworld keyword3 = new Keyworld("Liu_Shihao","#8600FF");
        Keyworld keyword4 = new Keyworld("15037196928","#46A3FF");
        Keyworld keyword5 = new Keyworld(Long.toString(l1),"#FFAD86");
        Keyworld keyword6 = new Keyworld(Long.toString(l4),"#7E3D76");
        Keyworld keyword7 = new Keyworld(Long.toString(l5),"#930000");


        //将data参数对象 转化成json
        JSONObject keyword00 = JSONObject.fromObject(keyword0);
        JSONObject keyword10 = JSONObject.fromObject(keyword1);
        JSONObject keyword20 = JSONObject.fromObject(keyword2);
        JSONObject keyword30 = JSONObject.fromObject(keyword3);
        JSONObject keyword40 = JSONObject.fromObject(keyword4);

        JSONObject keyword51 = JSONObject.fromObject(keyword5);
        JSONObject keyword61 = JSONObject.fromObject(keyword6);
        JSONObject keyword71 = JSONObject.fromObject(keyword7);

        //构造进  data参数
        JSONObject templateData2 = new JSONObject();
        templateData2.put("keyword0",keyword00);
        templateData2.put("keyword1",keyword10);
        templateData2.put("keyword2",keyword20);
        templateData2.put("keyword3",keyword30);
        templateData2.put("keyword4",keyword40);

        templateData2.put("keyword5",keyword51);
        templateData2.put("keyword6",keyword61);
        templateData2.put("keyword7",keyword71);


        //获得AccessToken
        String redisToken = wxService.getRedisToken();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
        String access_token = url.replace("ACCESS_TOKEN", redisToken);


        for (String openId : users) {


            //构造 请求参数对象
            WxTemplateMessage wxTemplateMessage1 = new WxTemplateMessage(openId, templateId, "https://blog.csdn.net/DreamsArchitects",null);

            //将请求参数对象  转化成 JSON
            JSONObject msgData = JSONObject.fromObject(wxTemplateMessage1);
            msgData.put("data",templateData2.toString());
            String post = httpClient(access_token, "POST", msgData.toString());
            log.info(post);


        }








    }

    public String httpClient(String Url,String RequestMethod,String data){
        StringBuffer sb = null;
        try {
            URL url = new URL(Url);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            String s = RequestMethod.toUpperCase();
            httpUrlConn.setRequestMethod(s);
            httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            if ("GET".equalsIgnoreCase(RequestMethod)){
                httpUrlConn.connect();
            }else {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpUrlConn.getOutputStream(), "UTF-8"));
                writer.write(data);
                writer.close();
            }
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            sb = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                sb.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpUrlConn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(sb);
        log.info(sb.toString());
        return sb.toString();
    }



}
